import axios, { AxiosRequestConfig, AxiosResponse } from 'axios'
import { Toast } from 'vant';
import store from '@/store';
const service = axios.create({
    baseURL: '/api',
    timeout: 50000
})
service.defaults.withCredentials = true;
service.interceptors.request.use(
    (config: AxiosRequestConfig) => {
        store.dispatch('loading/CHANGE_LOADING_ADD_ACTION')
        return config
    },
    error => {
        return Promise.reject(error)
    }
)
service.interceptors.response.use(
    (response: AxiosResponse<any>) => {
        store.dispatch('loading/CHANGE_LOADING_REDUCE_ACTION')
        const res = response.data
        if (response.status !== 200) {
            if (res.success) {
                return res
            }
            Toast.fail(res.message || res.msg || '请稍后再试')
            return Promise.reject(res)
        }
        return res
    },
    error => {
        const err = error?.response?.data || '';
        store.dispatch('loading/CHANGE_LOADING_REDUCE_ACTION')
        if (error.toString().indexOf('timeout') !== -1) {
            Toast.fail('网络超时,请稍后再试')
            return Promise.reject("请稍后再试")
        }
        Toast.fail(err.message || err.msg || '请稍后再试')
        return Promise.reject(err)
    }
)
export default service;